package exts

import (
	"context"
	"errors"
	"gitee.com/tietang/terrace-go/v2/base/plugin"
	"gitee.com/tietang/terrace-go/v2/example/order"
	"time"
)

var mtExt order.CreateOrderDomainExt = new(MtOrderCreatedDomainExt)
var _ plugin.RuleChecker = new(MtOrderCreatedDomainExt)
var _ plugin.PluginId = new(MtOrderCreatedDomainExt)
var _ plugin.Plugin = new(MtOrderCreatedDomainExt)

const (
	CreateOrderDomainExtpluginId = "mt"
)

func init() {
	mtExt := MtOrderCreatedDomainExt{}
	//m.CreateOrderDomainExt = &m
	mtExt.RuleChecker = plugin.ExprRuleChecker{
		PluginId: &mtExt,
	}
	plugin.Register(&mtExt)
}

type MtOrderCreatedDomainExt struct {
	order.CreateOrderDomainExt `ability:"Meituan"`
	RuleChecker                plugin.ExprRuleChecker
}

func (o *MtOrderCreatedDomainExt) Check(ctx context.Context, in interface{}) bool {
	return o.RuleChecker.Check(ctx, in)
}

func (o *MtOrderCreatedDomainExt) OnValidate(ctx context.Context, in *order.Order) error {
	if !in.TradeAmount.Equal(in.PayAmount) {
		return errors.New("交易金额和支付金额不一致")
	}
	return nil
}

func (o *MtOrderCreatedDomainExt) PreSave(ctx context.Context, in *order.Order) error {
	// MT 已支付状态
	in.Status = 1
	if in.BizDate == nil {
		//MT 凌晨2点之前算前一天营业日
		date := time.Now()
		date.Add(-time.Hour * 3)
		in.BizDate = &date
	}
	return nil
}

func (o *MtOrderCreatedDomainExt) PluginCode() string {
	return order.CreateOrderDomainPluginId
}
func (o *MtOrderCreatedDomainExt) Ability() string {
	return CreateOrderDomainExtpluginId
}
